<template>
	<div class="goods-share" id="goods-share">
		<van-skeleton :row-width="['40%', '100%', '90%', '100%', '30%', '100%', '100%', '40%', '100%', '100%']" :row="10" :loading="loading">
			<!--分享收益-->
			<div class="share-profit" v-if="goodsInfo">
				<h2>分享可赚¥{{ goodsInfo.couponCommissionApp | Fixed(2) }}</h2>
				<img src="@/assets/images/goods/share.png" />
			</div>

			<!-- 选择图片 -->
			<div class="select-images">
				<div class="select-status">
					<p>选择海报封面图</p>
					<!--<p>-->
					<!--已选<span>{{ selectCalc }}</span-->
					<!--&gt;张-->
					<!--</p>-->
				</div>
				<div class="images-list">
					<template v-for="(item, index) in images">
						<div class="images-item" :key="index" :class="[{ active: item.selectFlag }]" @click="selectPicture(item)" v-if="item.imgUrl">
							<img v-lazy="item.imgUrl" alt="" />
							<div class="mask"></div>
							<div class="select-flag"><van-icon name="success" /></div>
						</div>
					</template>
				</div>
			</div>

			<!-- 分享文案 -->
			<div class="share-tips">
				<label>编辑分享文案</label>
				<van-field v-model="message" rows="1" autosize type="textarea" placeholder="请输入分享文案" />
				<div class="share-desc">
					<p>编辑时请不要更改淘口令哦～</p>
					<a v-copy="message"><i class="iconfont icon-fuzhi"></i>复制分享文案</a>
				</div>
			</div>

			<!--创建分享-->
			<div class="share-footer">
				<a @click="createPoster">生成分享图</a>
			</div>
		</van-skeleton>

		<!--海报图预览-->
		<van-popup v-model="visible" closeable>
			<div class="poster">
				<img :src="this.poster" alt="" />
			</div>
			<!--分享到平台-->
			<div class="share-plat">
				<div class="share-title">
					<i></i>
					<p>图文分享到</p>
					<i></i>
				</div>
				<div class="plat-list">
					<div class="plat-item" @click="shareToPlat('weixin')">
						<img src="@/assets/images/goods/wechat.png" />
						<p>微信好友</p>
					</div>
					<div class="plat-item" @click="shareToPlat('weixinTimeline')">
						<img src="@/assets/images/goods/moments.png" />
						<p>朋友圈</p>
					</div>
					<div class="plat-item" @click="shareToPlat('qqFriend')">
						<img src="@/assets/images/goods/qq.png" />
						<p>QQ</p>
					</div>
					<div class="plat-item" @click="shareToPlat('qZone')">
						<img src="@/assets/images/goods/zone.png" />
						<p>QQ空间</p>
					</div>
					<div class="plat-item" @click="savePicture">
						<img src="@/assets/images/goods/save.png" />
						<p>一键保存</p>
					</div>
				</div>
			</div>
		</van-popup>
	</div>
</template>

<script>
import store from 'store';
import QRCode from 'qrcode';
import { Field, Skeleton, Popup, Toast } from 'vant';
export default {
	name: 'goods-share',
	components: {
		'van-field': Field,
		'van-skeleton': Skeleton,
		'van-popup': Popup
	},
	data() {
		return {
			loading: false,
			images: [],
			message: '',
			goodsInfo: null,
			tkl: null,
			poster: null,
			visible: false
		};
	},
	mounted() {
		document.getElementById('goods-share').style.minHeight = document.documentElement.clientHeight + 'px';
	},
	computed: {
		// 计算选中数量
		selectCalc() {
			let num = 0;
			this.images.forEach(item => {
				if (item.selectFlag) {
					num++;
				}
			});
			return num;
		}
	},
	created() {
		this.getGoodsDetail();

		// 检测当前设备分享渠道
		// this.checkSharing();
	},
	methods: {
		// 获取商品详情
		getGoodsDetail() {
			// 从缓存中读取商品信息
			if (Number(this.$route.query.superGoods) === 1) {
				this.loading = true;
				this.goodsInfo = store.get('goodsInfo');
				this.goodsInfo.endPrice = Number(this.goodsInfo.endPrice).toFixed(2);
				this.goodsInfo.price = Number(this.goodsInfo.price).toFixed(2);

				// 加载轮播图
				if (this.goodsInfo.taobaoImage) {
					let list = this.goodsInfo.taobaoImage.split(',');
					let tempArr = [];
					for (let i = 0; i < list.length; i++) {
						tempArr.push({
							imgUrl: list[i],
							selectFlag: false
						});
					}
					this.images = tempArr;
				} else {
					this.images = [
						{
							imgUrl: this.goodsInfo.pic,
							selectFlag: false
						}
					];
				}
				this.images[0].selectFlag = true;
				this.getPrivilege();
			} else {
				this.loading = true;
				let params = {
					skuId: this.$route.query.skuId
				};
				this.$service.jd.goods.detail(params).then(res => {
					this.goodsInfo = res || {};

					const imgList = JSON.parse(this.goodsInfo.imageList || '[]');

					// 加载轮播图
					if (imgList) {
						this.images = imgList.map(e => {
							return {
								imgUrl: e.url,
								selectFlag: false
							};
						});
					} else {
						this.images = [
							{
								imgUrl: this.goodsInfo.skuImage,
								selectFlag: false
							}
						];
					}
					this.images[0].selectFlag = true;
					this.getShortUrl();
				});
			}
		},
		// 获取短链接
		getShortUrl() {
			const { materialUrl, couponLink } = this.goodsInfo;

			const params = {
				materialUrl,
				couponLink
			};

			this.$service.jd.goods.createShortUrl(params).then(res => {
				this.goodsInfo.url = res;
				this.getShareTemplate();
			});
		},
		// 获取分享文案
		getShareTemplate() {
			let { skuName, price, lowestCouponPrice, url } = this.goodsInfo;

			price = parseFloat(price).toFixed(2);
			lowestCouponPrice = parseFloat(lowestCouponPrice).toFixed(2);

			this.message = `【${skuName}】\n【在售价】${price}元\n【券后价】${lowestCouponPrice}元\n-------------\n【下单链接】${url}\n》》应用商店下载【翼支付】享受更多优惠券商品`;
			this.loading = false;

			// this.$service.shopping.shareTemplate
			// 	.template({
			// 		type: 1,
			// 		playform: 1
			// 	})
			// 	.then(res => {
			// 		let template = res;
			// 		let newTemplate = '';
			// 		template.split('{').forEach(item => {
			// 			let t = item.split('}');
			// 			if (t.length === 2) {
			// 				newTemplate += this.goodsInfo[t[0]];
			// 				newTemplate += t[1];
			// 			} else {
			// 				newTemplate += item;
			// 			}
			// 		});
			// 		this.message = newTemplate;
			// 		this.loading = false;
			// 	});
		},
		// 选择取消图片
		selectPicture(item) {
			if (item.selectFlag) {
				item.selectFlag = !item.selectFlag;
			} else {
				this.images.forEach(itm => {
					itm.selectFlag = false;
				});
				item.selectFlag = true;
			}
		},
		// 保存图片到本地
		savePicture() {
			let imageBase64 = this.poster.substring(22);
			window.BestpayHtml5.Storage.savePicture(
				{
					base64ImageStream: imageBase64
				},
				() => {
					this.$toast('保存成功');
				}
			);
		},
		// 创建分享海报
		async createPoster() {
			// 读取选中图片
			let imgUrl = null;
			this.images.forEach(item => {
				if (item.selectFlag === true) {
					imgUrl = item.imgUrl;
				}
			});
			if (!imgUrl) {
				this.$toast('请选择海报封面图');
				return false;
			}

			// 开始创建
			Toast.loading({
				duration: 0, // 持续展示 toast
				forbidClick: true,
				message: '创建海报中...'
			});

			let vm = this;
			// 创建画布
			let canvas = document.createElement('canvas');
			canvas.width = 598;
			canvas.height = 968;
			let context = canvas.getContext('2d');
			context.rect(0, 0, canvas.width, canvas.height);

			// 绘制背景色
			context.fillStyle = '#FFFFFF';
			context.fillRect(0, 0, 598, 968);

			// 绘制商品标题
			this.drawText(context, this.goodsInfo.skuName, 24, 576, 550, 24, '#212121');

			// 绘制券后价
			this.drawText(context, Number(this.goodsInfo.lowestCouponPrice).toFixed(2), 114, 714, 500, 48, '#F70114');
			this.drawText(context, '券后价¥', 24, 716, 500, 24, '#F70114');

			// 绘制优惠券矩形、价格
			this.fillRoundRect(context, 380, 710, 202, 60, 12, '#F91015');
			this.drawText(context, '¥' + this.goodsInfo.couponDiscount, 390, 708, 500, 36, '#FFF7C9');
			this.drawText(context, '券', 536, 708, 500, 36, '#FFF7C9');
			this.drawText(context, '|', 514, 706, 500, 36, '#FFF7C9');

			// 绘制原价销量
			this.drawText(
				context,
				'原价 ¥' + parseFloat(this.goodsInfo.price).toFixed(2) + '       销量' + this.goodsInfo.inOrderCount30Days,
				24,
				770,
				500,
				24,
				'#717076'
			);
			this.drawText(context, '————', 70, 770, 500, 24, '#717076');

			// 绘制app名称
			this.drawText(context, '赚分享', 98, 860, 500, 24, '#F70114');
			this.drawText(context, '下载【翼支付】进入【赚分享】领取更多优惠补贴', 98, 890, 500, 15, '#717076');
			this.drawText(context, '长按识别二维码', 452, 910, 500, 18, '#717076');

			// 生成海报二维码
			let qrBase64 = await QRCode.toDataURL(this.goodsInfo.url, {
				errorCorrectionLevel: 'H',
				type: 'image/jpeg',
				margin: 1
			});

			// 绘制商品图
			let goodsImage = new Image();
			goodsImage.setAttribute('crossOrigin', 'Anonymous');
			goodsImage.src = imgUrl;
			goodsImage.onload = function() {
				context.drawImage(goodsImage, 18, 18, 564, 564);

				// 绘制app logo
				let logoBase64 =
					'';
				let logoImage = new Image();
				logoImage.src = logoBase64;
				logoImage.onload = function() {
					context.drawImage(logoImage, 24, 880, 56, 56);

					// 绘制海报二维码
					let qrImage = new Image();
					qrImage.setAttribute('crossOrigin', 'Anonymous');
					qrImage.src = qrBase64;
					qrImage.onload = function() {
						context.drawImage(qrImage, 446, 794, 136, 136);

						let base64 = canvas.toDataURL('image/png');

						vm.poster = base64;

						// 清除提示
						setTimeout(() => {
							Toast.clear();
							vm.visible = true;
						}, 1000);
					};
				};
			};
		},
		// 绘制圆角矩形
		fillRoundRect(cxt, x, y, width, height, radius, fillColor) {
			//圆的直径必然要小于矩形的宽高
			if (2 * radius > width || 2 * radius > height) {
				return false;
			}

			cxt.save();
			cxt.translate(x, y);
			//绘制圆角矩形的各个边
			this.drawRoundRectPath(cxt, width, height, radius);
			cxt.fillStyle = fillColor || '#000'; //若是给定了值就用给定的值否则给予默认值
			cxt.fill();
			cxt.restore();
		},
		// 绘制圆角矩形
		drawRoundRectPath(cxt, width, height, radius) {
			cxt.beginPath(0);
			//从右下角顺时针绘制，弧度从0到1/2PI
			cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
			//矩形下边线
			cxt.lineTo(radius, height);
			//左下角圆弧，弧度从1/2PI到PI
			cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
			//矩形左边线
			cxt.lineTo(0, radius);
			//左上角圆弧，弧度从PI到3/2PI
			cxt.arc(radius, radius, radius, Math.PI, (Math.PI * 3) / 2);
			//上边线
			cxt.lineTo(width - radius, 0);
			//右上角圆弧
			cxt.arc(width - radius, radius, radius, (Math.PI * 3) / 2, Math.PI * 2);
			//右边线
			cxt.lineTo(width, height - radius);
			cxt.closePath();
		},
		// 绘制文字
		drawText(cxt, t, x, y, w, size, color) {
			let chr = t.split('');
			let temp = '';
			let row = [];

			cxt.font = size + 'px Arial';
			cxt.fillStyle = color;
			cxt.textBaseline = 'middle';

			for (let a = 0; a < chr.length; a++) {
				// eslint-disable-next-line
				if (cxt.measureText(temp).width < w) {
				} else {
					row.push(temp);
					temp = '';
				}
				temp += chr[a];
			}
			row.push(temp);
			for (let b = 0; b < row.length; b++) {
				cxt.fillText(row[b], x, y + (b + 1) * 35);
			}
		},
		shareToPlat(type) {
			let imageBase64 = this.poster.substring(22);
			window.BestpayHtml5.Other.share({
				imageData: imageBase64, //图片base64(不需要加前缀)
				type: type,
				contentType: 'image'
			});
		}
	},
	destroyed() {
		Toast.clear();
	}
};
</script>

<style lang="scss" scoped>
.goods-share {
	background: $color-white;
	min-height: 100%;
	padding-bottom: 124px;
	.share-profit {
		background: $color-white;
		h2 {
			color: $main-color;
			font-size: 36px;
			font-weight: 600;
			padding-top: 52px;
			margin-bottom: 22px;
			text-align: center;
		}
		img {
			width: 100%;
		}
	}
	.select-images {
		width: 100%;
		.select-status {
			color: $text-black;
			font-size: 28px;
			padding: 0 30px 20px;
			font-weight: 600;
			@include flexBox(space-between);
			span {
				color: $main-color;
			}
		}
		.images-list {
			width: 100%;
			overflow-x: auto;
			white-space: nowrap;
			.images-item {
				width: 178px;
				height: 178px;
				margin-left: 24px;
				display: inline-block;
				position: relative;
				border-radius: 16px;
				overflow: hidden;
				img {
					max-width: 100%;
					max-height: 100%;
				}
				.mask {
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
					overflow: hidden;
					background: rgba(0, 0, 0, 0.4);
					border-radius: 16px;
					transition: 0.5s;
				}
				.select-flag {
					opacity: 0;
					transition: 0.5s;
					width: 0;
					height: 0;
					position: absolute;
					right: 0;
					bottom: 0;
					border-bottom: 50px solid red;
					border-left: 50px solid transparent;
					/deep/.van-icon {
						position: absolute;
						left: -30px;
						top: 20px;
						font-size: 28px;
						color: $color-white;
					}
				}
				&:last-child {
					margin-right: 24px;
				}
				&.active {
					.mask {
						opacity: 0;
					}
					.select-flag {
						opacity: 1;
					}
				}
			}
		}
	}
	.share-tips {
		padding: 20px 30px;
		label {
			color: $text-black;
			font-size: 28px;
			margin-bottom: 30px;
			font-weight: 600;
			display: block;
		}
		/deep/.van-cell {
			background: #f7f7f7;
			border-radius: 28px;
			padding: 20px 30px;
			.van-field__control {
				min-height: 150px !important;
				font-size: 24px;
				color: #000;
			}
		}
		.share-desc {
			font-size: 28px;
			margin-top: 30px;
			@include flexBox(space-between);
			p {
				color: #6a6a6a;
			}
			a {
				color: #ef5b40;
				i {
					margin-right: 8px;
				}
			}
		}
	}
	.share-footer {
		width: 100%;
		height: 124px;
		position: fixed;
		bottom: 0;
		@include flexBox(center, center);
		a {
			width: 672px;
			line-height: 80px;
			font-size: 28px;
			background: #f71011;
			border-radius: 50px;
			color: $color-white;
			text-align: center;
		}
	}
	.van-skeleton {
		padding: 30px;
		@include flexBox(null, null, column);
		.van-skeleton__row {
			border-radius: 8px;
			&:nth-child(2) {
				height: 120px;
				margin: 20px auto 0;
			}
			&:nth-child(4) {
				height: 180px;
				margin: 20px auto 0;
			}
			&:nth-child(6) {
				height: 450px;
				margin: 20px auto 0;
			}
			&:nth-child(9) {
				height: 150px;
				margin: 20px auto 0;
			}
		}
	}
}
.van-popup {
	width: 100%;
	height: 100%;
	background: none;
	.poster {
		height: 68%;
		img {
			margin: 26px auto;
			width: unset;
			display: block;
			max-width: 100%;
			max-height: 100%;
		}
	}
	.share-plat {
		padding: 44px 30px;
		width: 100%;
		position: fixed;
		bottom: 0;
		background: $color-white;
		.share-title {
			font-size: 28px;
			color: #000;
			@include flexBox(space-between, center);
			i {
				width: 260px;
				height: 2px;
				background: #e7e7e7;
			}
		}
		.plat-list {
			margin-top: 40px;
			@include flexBox(space-between);
			.plat-item {
				width: 120px;
				text-align: center;
				img {
					width: 90px;
					height: 90px;
				}
				p {
					font-size: 24px;
				}
			}
		}
	}
}
// 判断iphoneX 将 footerBox 的 padding-bottom 填充到最底部
@supports (bottom: env(safe-area-inset-bottom)) {
	.share-footer {
		padding-bottom: env(safe-area-inset-bottom);
	}
}
</style>
